import store from '@/store/store.js'
import {
  getUserInfoByCode,
  getToken,
  getMiddleInfo
} from '@/common/api/user_api.js'
import {
  addLog
} from '@/common/api/index_api.js'
import {
  showToast,
  parseKeyValueString,
  removeEmptyProperty,
  parseQueryString
} from '@/common/utils/util.js'

export default {
  /**
   * 每次进入都要初始化登录
   */
  initMpLogin(options) {
    
    // if(uni.getStorageSync('isFromEshopLink')){
    //   uni.reLaunch({
    //     url: '/pages/sclList/sclList?paramObj=' + JSON.stringify(options)
    //   })
    //   return false
    // }
    // return
    if(options && options.inviteId){
      uni.setStorageSync('inviteId',options.inviteId)
    }
    const that = this
    console.log('initMpLogin - opt：', options);
    return new Promise((reosove, reject) => {
      uni.login({
        async success(res) {
          console.log(options.adType,'===options.adType')
          console.log(res,'=========res')
          const {
            data : firstRes
          } = await getToken({
            code:res.code
          })
          
          if(options.p && options.mId){
            const {data:pRes} = await getMiddleInfo({mId:options.mId})
            console.log('pRes：',pRes)
            if(pRes.data){
              options = parseQueryString(pRes.data)
              console.log('options-options：',options)
            }
          }
          
          if(firstRes.code == 200){
            uni.setStorageSync('ttToken',firstRes.data)
          }else{
            // return that.$showToast('获取Token失败,请重启小程序')
            return uni.showToast({
              icon: 'none',
              title: '获取Token失败,请重启小程序',
            })
          }
              
          
                    
          if (options.scene && !options.adType){
            //如果是通过二维码进来的，且原参数无adType，则添加adType参数
          	const tmp_data = parseKeyValueString(decodeURIComponent(options.scene))
          	if(tmp_data && tmp_data.d){
          		options.adType = tmp_data.d
          	}
            
            console.log(options.adType,'====options.adType=')
          }
          
          if(!options.adType && options.d){
            options.adType = options.d
          }
          
          
          const {
            data: dRes
          } = await getUserInfoByCode(removeEmptyProperty({
            adType: options.adType,
            clientUserId: uni.getStorageSync('inviteId'),
			teamId:options.teamId,//通过某个团体测评进入tt
			teamUuId:options.teamUuId,//某个团体测评的用户
			platform:uni.getSystemInfoSync().platform
          }))
          uni.hideLoading() 
          //小程序登录授权接口

          if (dRes.code == 200) {
            console.log('-------------------------------dc-----------------------')
            console.log(dRes,'=====dRes ---- isShowEconsultModal')
            const userInfo = Object.assign(dRes.data.user, {
              token: dRes.data.token
            });

            const roles = Object.assign([], dRes.data.roles)

            userInfo.hasRecptionCasePermission = userInfo.roles?.includes("storesSell");

            uni.setStorageSync('balanceFlag', '1') //改变状态获取用户权益

            store.commit('user/setPurchaseAndUsageCount', dRes.data.transactionCount)
            store.commit('user/setUserInfo', userInfo)
            store.commit('user/setUserChannel',dRes.data.userChannel)
            store.commit('user/setInviterId',dRes.data.inviter)
            store.commit('user/setIsOldUser',!!dRes.data.oldUser)
            store.commit('user/setIsPaySclExamination',!!dRes.data.isPaySclExamination)
            store.commit('user/setNewUserCouponModalShow',!!dRes.data.newUser)
            store.commit('user/setIsShowEconsultBlock',dRes.data.userRightsOnline)
            store.commit('user/setIsShowEconsultModal',dRes.data.giveEarTo)
            console.log(dRes.data,'========dRes.data.scloneGoods')
            store.commit('user/setNotUseLbYiyuan',!!dRes.data.sclOneGoods)
            // store.commit('user/setIsOldUser',true)
            store.commit('user/setRoles', roles)
            store.commit('user/setCurrentGroup', dRes.data.groupInfo)
            store.commit('user/setIsVip',dRes.data.member)
            console.log(dRes.data,'-----dRes.data')
            store.commit('user/setCouponFirstMonthTime',dRes.data.discountTime)
            store.dispatch('app/getQrcodeInfo')
            store.dispatch('user/getUserDiscountInfo')
            store.dispatch('user/getIsMember')
          } else {
            store.commit('user/setUserInfo', {})
            let adClick = uni.getStorageSync('adClickId')
            uni.clearStorageSync();
            uni.setStorageSync('adClickId',adClick)
          }
          
          try{
            if(options.ad || options.adType){
              store.commit('user/setAdType',options.adType || options.ad)
            }
          }catch(e){
            console.log('nothing-to-happend：',e);
          }
          if (options.userType == 'e-commerce') { //电商用户跳转测评
            uni.reLaunch({
              url: '/pages/sclList/sclList?paramObj=' + JSON.stringify(options)
            })
          }else if (options.userType == 'task-center') { //通过公众号进入的
            options.from = 'offical'
            console.log('--------跳环')
            uni.redirectTo({
              url: '/subcontractorC/pages/taskCenter/taskCenter?paramObj=' + JSON.stringify(options)
            })        
          } else if (options.userType  == 'sclShare') {
            
            addLog({sclId:options.sclId,sourseType:11})
            uni.reLaunch({
              url: '/subcontractorC/pages/sclIntroduce/sclIntroduce?paramObj=' + JSON.stringify(options)
            })
          } else if (options.userType == 'sclCheckup') {//跳转个人心理健康体检
            uni.reLaunch({
              url: '/subcontractorC/pages/sclCheckup/sclCheckup?sourceType=' + options.sourceType
            })
          } else if (options.userType == 'sclSearch') {//跳转测评大厅搜索
            uni.reLaunch({
              url: '/subcontractorC/pages/sclSearch/sclSearch'
            })
          } else if (options.userType == 'sclList') {
            uni.reLaunch({
              url: '/pages/sclList/sclList?paramObj=' + JSON.stringify(options)
            })
          }else if (options.sclResultParams) {
			  uni.reLaunch({
			    url:'/pages/sclList/sclList?sclResultParams='+options.sclResultParams
			  })
          } else if (options.userType == 'course') {
            uni.reLaunch({
              url: '/pages/course/course'
            })
          } else if (options.userType == 'checkupDepressed') {
            uni.reLaunch({
              url: '/subcontractorC/pages/checkupDepressed/index?sourceType=' + options.sourceType
            })
          } else if (options.userType == 'e-consult') {
            uni.reLaunch({
              url: '/subcontractorA/pages/eshopConsult/eshopConsult'
            })
          } else if (options.userType == 'sclMore') {
            uni.reLaunch({
              url: '/pages/sclList/sclList?paramObj=' + JSON.stringify(options)
            })
          } else if (options.userType == 'article') {
            uni.reLaunch({
              url: '/subcontractorC/pages/courseArticle/courseArticle?id=' + options.id
            })
          }else if (options.userType == 'conselorDetail') {
            uni.reLaunch({
              url: '/subcontractorA/consultantDetails/consultantDetails?consultantId=' + options.consultantId
            })
          } else if (options.userType == 'check-up') {
            uni.redirectTo({
              url: '/subcontractorC/pages/sclCheckup/sclCheckup?sourseType=11'
            })
          } else if (options.userType == 'ai') {
            uni.redirectTo({
              url: '/subcontractorC/pages/AI/index'
            })
          } else if (options.userType == 'video') {
            uni.reLaunch({
              url: '/subcontractorC/pages/courseVideo/courseVideo?id=' + options.id
            })
          } else if (options.userType == 'sexuality-assessment') {
            uni.redirectTo({
              url: '/subcontractorC/pages/sexuality-assessment/index'
            })
          } else if (options.userType == 'mailun') {
            uni.reLaunch({
              url: '/pages/sclList/sclList?currentIndexPage=1'
            })
          }else if (options.userType == 'mailunBefore') {//脉轮先付后测
            uni.reLaunch({
              url: '/subcontractorMaiLun/pages/introduce/introduce?isBeforePay=1'
            })
          }else if (options.userType == 'mailunAfter') {//脉轮先测后付
            uni.reLaunch({
              url: '/subcontractorMaiLun/pages/introduce/introduce?isAfterPay=1'
            })
          } else if (options.scene || options.p|| options.r) {
			  console.log(options,'新增放开r,,,,scene在这里获取不到，待测试')
            if (dRes.code == 200) {
              let tmpData
              if(options.scene){
                tmpData = parseKeyValueString(decodeURIComponent(options.scene))
              }else{
                tmpData = options
              }
              console.log(tmpData,'======tmpData')
              if(tmpData.r == 5 && tmpData.p == 1){
                uni.reLaunch({
                  url: '/subcontractorC/pages/sclCheckup/sclCheckup?sourceType=11'
                })
              }else if(tmpData.p == 2){
                uni.reLaunch({
                  url: '/subcontractorC/pages/sclIntroduce/sclIntroduce?paramObj=' + JSON.stringify({
                    userType:'sclShare',
                    sclId:tmpData.id
                  })
                })
              } else if (tmpData.p == '13') {
                // 接待信息
                uni.redirectTo({
                  url: `/subcontractorA/case/caseDetail/caseDetail?id=${tmpData.id}`
                })
              }else{
                store.dispatch('app/checkScanParamsToAction')
              }
            }else {
              const tmpData = parseKeyValueString(decodeURIComponent(options.scene))
              uni.redirectTo({
                url: '/subcontractorA/authorization/authorization?paramObj=' +
                  JSON.stringify(tmpData)
              })
              
              // uni.redirectTo({
              //   url: '/subcontractorA/wxLogin/wxLogin?paramObj=' + JSON.stringify(tmpData)
              // })
            }
          } else {
            if(options.userType == 'ad' || options.ad == '4' || options.ad == '3' || options.adType == '2'){
              store.commit('user/setAdType',options.adType || options.ad)
              if(options.ad == '4' || options.adType == '6'){
                addLog({sclId:'1748233507262767105',sourseType:11})
               uni.reLaunch({
                 url: '/subcontractorC/pages/sclIntroduce/sclIntroduce?paramObj=' + JSON.stringify({
                   userType:'sclShare',
                   sclId:'1748233507262767105' //繁花测评海报
                 })
               }) 
               return
              }else if(options.t=='scl'){
                uni.reLaunch({
                  url: '/pages/sclList/sclList'
                })
                return
              }
            }
            uni.reLaunch({
              url: '/pages/sclList/sclList'
            })
          }
          
          

        }

      })

    })
  },
}